package com.zjinyin.forum.interceptor;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-08-10
 * Time: 10:42
 */

import com.zjinyin.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登陆拦截器
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    // 将配置文件中定义的值读取赋值到指定变量
    @Value("${forum.login.url}")
    private String DEFAULT_URL;

    /**
     * 拦截器的前置处理
     * @param request 请求
     * @param response 响应
     * @param handler 处理器
     * @return true : 指定逻辑通过, 执行后续代码流程 <br></br> false : 直接中断后续流程
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1. 获取登陆会话
        HttpSession session = request.getSession(false);

        // 2. 判断 session
        if(session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            return true;
        }

        // 没有权限, 强制跳转登录
        //  '/' 防止拼接 URL 错误, 需要检验 URL
        if(!DEFAULT_URL.startsWith("/")) {
            DEFAULT_URL = "/" + DEFAULT_URL;
        }

        response.sendRedirect(DEFAULT_URL);
        return false;
    }
}
